package handler

import (
	"cloud-disk/logic"
	"cloud-disk/model/request"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

// CreateShareHandler 分享文件 支持批量分享 但是只支持同级
func CreateShareHandler(c *gin.Context) {
	userIdentity := c.GetString("identity")
	req := request.CreateShare{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	if len(req.ParentIds) != len(req.Identities) {
		c.JSON(http.StatusOK, gin.H{
			"msg": "must same level",
		})
		return
	}
	for i := 0; i < len(req.ParentIds)-1; i++ {
		if req.ParentIds[i] != req.ParentIds[i+1] {
			c.JSON(http.StatusOK, gin.H{
				"msg": "parameter error",
			})
			return
		}
	}
	resp, err := logic.CreateShareLogic(userIdentity, req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, *resp)
}

// AccessShareFileHandler access files
func AccessShareFileHandler(c *gin.Context) {
	req := request.AccessShareFile{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	// check code is correct
	resp, err := logic.AccessShareFileLogic(req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, *resp)
}

func SaveShareHandler(c *gin.Context) {
	identity := c.GetString("identity")
	req := request.SaveShare{}
	c.BindJSON(&req)
	err := logic.SaveShareLogic(identity, req.ParentId, req.OriginRepoInfo)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")
}
